/**
 * author:0283000106
 */
package com.zte.claa.inficombo.csa.app.service.gprs.mina;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zte.claa.inficombo.csa.app.service.gprs.bean.GPRSDevCommand;
import com.zte.claa.inficombo.csa.app.service.rptparse.CRC16M;


public class GPRSDevMsgEncoder implements MessageEncoder<GPRSDevCommand> {
	private static final Logger logger = LoggerFactory.getLogger(GPRSDevMsgEncoder.class);
	// 字符集
	private Charset charset = null;
	private CharsetEncoder charsetEncoder = null;

	public GPRSDevMsgEncoder(Charset charset) {
		this.charset = charset;
		if (this.charset == null) {
			this.charset = Charset.forName("UTF-8");
		}
		this.charsetEncoder = this.charset.newEncoder();
	}

	/**
	 * 编码方法.
	 */
	public void encode(IoSession session, GPRSDevCommand message, ProtocolEncoderOutput out) throws Exception {
		logger.info("Begin encode message for session: " + session.getId()+", msg: "+message);
		IoBuffer buf = IoBuffer.allocate(message.getPaylen()+1).setAutoExpand(true);
		byte[] bstmp = CRC16M.getSendBufBigEnd(message.getPayload());
		if(null == bstmp){
			logger.info("Send data need encoding for session is null. sessionid: " + session.getId());
			return;
		}
		buf.put(bstmp);
		// 整理buf，准备输出数据
		buf.flip();
		logger.info("Finish encoding for session: " + session.getId());
		out.write(buf);		
		//out.flush();
		logger.info("[send data]="+buf.getHexDump());
		buf.free();
		buf = null;
	}

}